package com.beasts.antpage.core.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * @author Locker
 * @date 09/07/2018 9:29 AM
 * @since 1.0
 */
public class DateUtil {

    /**
     * All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
     */
    public static final TimeZone UTC;


    /**
     * @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
     */
    public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";


    /**
     * 0001-01-01T00:00:00.000Z
     */
    public static final Date BEGINNING_OF_TIME;


    /**
     * 292278994-08-17T07:12:55.807Z
     */
    public static final Date END_OF_TIME;


    static {
        UTC = TimeZone.getTimeZone("UTC");
        TimeZone.setDefault(UTC);
        final Calendar c = new GregorianCalendar(UTC);
        c.set(1, 0, 1, 0, 0, 0);
        c.set(Calendar.MILLISECOND, 0);
        BEGINNING_OF_TIME = c.getTime();
        c.setTime(new Date(Long.MAX_VALUE));
        END_OF_TIME = c.getTime();
    }


    /**
     * "2018-07-13T01:08:54.787Z" 转为 Date
     */
    public static Date str2Date (String s) {
        SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
        sdf.setTimeZone(UTC);
        try {
            return sdf.parse(dateStringValidParse(s));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 时间字符串转换，去掉特殊字符等
     * @param s
     * @return
     */
    public static String dateStringValidParse (String s) {
        return s.replace("\"", "");
    }

}
